package com.org.qrtrace.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.org.qrtrace.Entry.response.ProductResponse;
import com.org.qrtrace.pojo.Checkhistory;
import com.org.qrtrace.pojo.Phistory;
import com.org.qrtrace.pojo.Product;
import com.org.qrtrace.pojo.Ptype;
import com.org.qrtrace.service.ICheckhistoryService;
import com.org.qrtrace.service.IPhistoryService;
import com.org.qrtrace.service.IProductService;
import com.org.qrtrace.service.IPtypeService;
import com.org.qrtrace.utils.CommonDefines;
import com.org.qrtrace.utils.CommonUtils;
import com.org.qrtrace.utils.JsonResult;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bonnie
 * @since 2023-03-18
 */
@RestController
@RequestMapping("/product")
@Api(tags = "产品管理api")
public class ProductController {
    @Autowired
    private IProductService service;
    @Autowired
    private IPtypeService ptypeService;
    @Autowired
    private IPhistoryService phistoryService;
    @GetMapping("/lists")
    public JsonResult<?> getList(){
        List<Product> products = service.list();
        List<ProductResponse> responseList = new ArrayList<>();
        for (Product product:products) {
            ProductResponse productResponse =ProductResponse.product2Response(product);
            QueryWrapper<Phistory> wrapper = new QueryWrapper<>();
            wrapper.eq("puid",product.getPuid());
            wrapper.eq("next_source",product.getAddress());
            wrapper.select().orderByDesc("create_time");
            wrapper.last("limit 1");
            Phistory phistory;
            try {
                phistory = phistoryService.getOne(wrapper);
            }catch (Exception e){
                return JsonResult.fail("操作失败！");
            }
            if (phistory == null) {
                productResponse.setArrived(CommonDefines.NOT_ARRIVED);
            }else {
                productResponse.setArrived(phistory.getArrived());
            }
            responseList.add(productResponse);
        }
        return JsonResult.successInfo(responseList);
    }

    @PostMapping("/add")
    public JsonResult<?> addProduct(Product product, HttpServletRequest request) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        CommonUtils.setTimeAndUser(product,request);
        product.setPuid(CommonUtils.getUUID());
        String typeName = product.getType();
        QueryWrapper<Ptype> wrapper = new QueryWrapper<>();
        wrapper.eq("type",typeName);
        Ptype type = ptypeService.getOne(wrapper);
        if(type == null){
            return JsonResult.fail("无此产品类型,请先添加！");
        }
        product.setTuid(type.getTuid());
        product.setType(typeName);
        if(service.save(product) && createHistory(product,"产品创建记录",product.getSource())){
            return JsonResult.success();
        }else {
            return JsonResult.fail("添加失败！");
        }
    }

    private boolean createHistory(Product product,String mark,String lastSource){
        Phistory phistory = new Phistory();
        phistory.setCreateTime(product.getCreateTime());
        phistory.setCreateBy(product.getCreateBy());
        phistory.setPuid(product.getPuid());
        phistory.setArrived(CommonDefines.NOT_ARRIVED);
        phistory.setLastSource(lastSource);
        phistory.setNextSource(product.getAddress());
        phistory.setMark(mark);
        phistory.setType(product.getType());
        phistory.setCuid(CommonUtils.getUUID());
        return phistoryService.save(phistory);
    }

    @PostMapping("/delete")
    public JsonResult<?> deleteProduct(Product product){
        QueryWrapper<Phistory> wrapper = new QueryWrapper<>();
        wrapper.eq("puid",product.getPuid());
        if(service.removeById(product) && phistoryService.remove(wrapper)){
            return JsonResult.success();
        }else{
            return JsonResult.fail("删除失败！");
        }
    }

    @PostMapping("/update")
    public JsonResult<?> updateProduct(Product product){
        if(service.updateById(product)){
            return JsonResult.success();
        }else{
            return JsonResult.fail("更新失败！");
        }
    }

    @GetMapping("/getData")
    public JsonResult<?> getData(Product product){
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.like("p_name",product.getPName());
        List<Product> list = service.list(wrapper);
        if(list.size()>0){
            return JsonResult.successInfo(list.toArray());
        }else {
            return JsonResult.fail("未查询到相关数据！");
        }
    }

    @GetMapping("/getById")
    public JsonResult<?> getById(Product product){
        Product res = service.getById(product);
        if(res!=null){
            return JsonResult.successInfo(res);
        }else {
            return JsonResult.fail("未查询到相关数据！");
        }
    }

    @PostMapping("/updatePosition")
    public JsonResult<?> updatePosition(Product product){
        Product old = service.getById(product);
        product.setCreateTime(LocalDateTime.now());
        if(service.updateById(product) && createHistory(product,old.getAddress()+"运输到"+product.getAddress(),old.getAddress())){
            return JsonResult.success();
        }else {
            return JsonResult.fail("操作失败！");
        }
    }


}
